package vip.aster.system.security;

import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;
import vip.aster.common.constant.Constants;
import vip.aster.common.constant.enums.LoginOperationEnum;
import vip.aster.framework.security.entity.UserDetail;
import vip.aster.system.service.SysLogLoginService;

/**
 * 认证事件处理
 *
 * @author Aster
 * @since 2023/12/1 10:05
 */
@Component
@AllArgsConstructor
public class AuthenticationEvents {
    private final SysLogLoginService sysLogLoginService;
    @EventListener
    public void onSuccess(AuthenticationSuccessEvent event) {
        // 用户信息
        UserDetail user = (UserDetail) event.getAuthentication().getPrincipal();

        // 保存登录日志
        sysLogLoginService.save(user.getId(), user.getUsername(), Constants.SUCCESS,
                LoginOperationEnum.LOGIN_SUCCESS.getValue(), user.getTenantId());
    }

    @EventListener
    public void onFailure(AbstractAuthenticationFailureEvent event) {
        // 用户名
        String username = (String) event.getAuthentication().getPrincipal();

        // 保存登录日志
        sysLogLoginService.save(null, username, Constants.FAIL, LoginOperationEnum.ACCOUNT_FAIL.getValue(), null);
    }
}
